package com.sgu6.sgu6_machine.ui.fragment.set;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.sgu6.middleware.enums.MachineCmdEnum;
import com.sgu6.middleware.event.MakeRiceEvent;
import com.sgu6.middleware.log.Logger;
import com.sgu6.middleware.manager.ThreadManager;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.redis.dto.ListGoodsSimpleDto;
import com.sgu6.serialport.manager.SerialPortManager;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.base.BaseF;
import com.sgu6.sgu6_machine.common.Constant;
import com.sgu6.sgu6_machine.container.GoodsContainer;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.dto.MakeRecordDto;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.task.MillTimeoutRunnable;
import com.sgu6.sgu6_machine.ui.activity.MachineManagerA;
import com.sgu6.sgu6_machine.ui.views.AmountView;
import com.sgu6.sgu6_machine.util.GoodsUtils;
import com.sgu6.sgu6_machine.util.MillCountUtil;
import com.sgu6.sgu6_machine.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MachineTestF extends BaseF {

    @BindView(R.id.atPackageWeight)
    AmountView atPackageWeight;
    @BindView(R.id.atMillNo)
    AmountView atMillNo;
    @BindView(R.id.tvMillCount)
    TextView tvMillCount;
    @BindView(R.id.atPackNo)
    AmountView atPackNo;
    @BindView(R.id.tv_pack_label)
    TextView tvPackLabel;
    @BindView(R.id.btnPack)
    Button btnPack;


    int count = 0; //当前碾米总数
    int curType = 0;//当前碾米类型，0胚芽米，1精胚米，2糙米
    MachineManagerA mContext;
    @BindView(R.id.ll_pack)
    LinearLayout llPack;

    @BindView(R.id.tv_mode)
    TextView tvMode;
    @BindView(R.id.btn_open_door_mode)
    Button btnOpenDoorMode;
    @BindView(R.id.btn_close_door_mode)
    Button btnCloseDoorMode;

    @BindView(R.id.btnClearWarnA)
    Button btnClearWarnA;
    @BindView(R.id.btnClearWarnB)
    Button btnClearWarnB;
    @BindView(R.id.btn_open_send_valley)
    Button btnOpenSendValley;
    @BindView(R.id.btn_close_send_valley)
    Button btnCloseSendValley;
    @BindView(R.id.btn_open_lamp)
    Button btnOpenLamp;
    @BindView(R.id.btn_close_lamp)
    Button btnCloseLamp;
    @BindView(R.id.btn_open_lock_mode)
    Button btnOpenLockMode;
    @BindView(R.id.btn_close_lock_mode)
    Button btnCloseLockMode;
    @BindView(R.id.btn_A)
    Button btnA;
    @BindView(R.id.btn_B)
    Button btnB;
    @BindView(R.id.btn_AB)
    Button btnAB;
    private MachineP machineP = new MachineP();

    private List<ListGoodsSimpleDto> listGoodsSimpleDtos;
    private Handler handler = new Handler();
    private MillTimeoutRunnable runnable = new MillTimeoutRunnable();

    public static MachineTestF newInstance() {
        return new MachineTestF();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_machine_test, container, false);
        unbinder = ButterKnife.bind(this, v);
        mContext = (MachineManagerA) getActivity();
        tvMode.setText("当前模式：".concat(getModeString()).concat("，").concat(getGarnerString()));
//        if (MachineContainer.machineConfigDto.withPack) {
//            btnOpenDoorMode.setVisibility(View.GONE);
//            btnCloseDoorMode.setVisibility(View.GONE);
//        }
        initUI();

        listGoodsSimpleDtos = GoodsUtils.read();

        return v;
    }

    public void initUI() {
        if (!MachineContainer.machineConfigDto.merchantId.equals(Constant.SGU6_MERCHANT_ID)) {
            tvMode.setVisibility(View.GONE);
            btnCloseLamp.setVisibility(View.GONE);
            btnOpenLamp.setVisibility(View.GONE);
            btnCloseLockMode.setVisibility(View.GONE);
            btnOpenLockMode.setVisibility(View.GONE);
            btnCloseSendValley.setVisibility(View.GONE);
            btnOpenSendValley.setVisibility(View.GONE);
            btnA.setVisibility(View.GONE);
            btnB.setVisibility(View.GONE);
            btnAB.setVisibility(View.GONE);
        } else {
            tvMode.setVisibility(View.VISIBLE);
            btnCloseLamp.setVisibility(View.VISIBLE);
            btnOpenLamp.setVisibility(View.VISIBLE);
            btnCloseLockMode.setVisibility(View.VISIBLE);
            btnOpenLockMode.setVisibility(View.VISIBLE);
            btnCloseSendValley.setVisibility(View.VISIBLE);
            btnOpenSendValley.setVisibility(View.VISIBLE);
            btnA.setVisibility(View.VISIBLE);
            btnB.setVisibility(View.VISIBLE);
            btnAB.setVisibility(View.VISIBLE);
        }

        if (!MachineContainer.machineConfigDto.withPack) {
            llPack.setVisibility(View.GONE);
        } else {
            btnClearWarnA.setVisibility(View.GONE);
            btnClearWarnB.setVisibility(View.GONE);
        }

        atPackageWeight.setDefaultValue(MachineContainer.machineConfigDto.packageWeight);
        atMillNo.setDefaultValue(MachineContainer.machineConfigDto.millNo);
        atPackNo.setDefaultValue(MachineContainer.machineConfigDto.packNo);

        atMillNo.setAmountMaxValue(10);
        atPackageWeight.setAmountMaxValue(530);
        atPackNo.setAmountMaxValue(10);
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        handler = null;
    }

    @OnClick({R.id.btnMillC, R.id.btnMillJ, R.id.btnMillP, R.id.btnMill, R.id.btnPack, R.id.btnClearWarnA, R.id.btnClearWarnB, R.id.btn_close_door_mode, R.id.btn_close_lock_mode, R.id.btn_open_send_valley, R.id.btn_close_send_valley, R.id.btn_open_door_mode, R.id.btn_open_lock_mode, R.id.btn_open_lamp, R.id.btn_close_lamp, R.id.btn_A, R.id.btn_B, R.id.btn_AB})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnMillC:
                curType = 2;
                StringBuilder sc = new StringBuilder(MachineCmdEnum.糙米.code());
                //5AA509820043000100070000
                sc.replace(15, 16, String.valueOf(MachineContainer.machineConfigDto.mode));
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(sc.toString()));
                break;
            case R.id.btnMillJ:
                curType = 1;
                StringBuilder sj = new StringBuilder(MachineCmdEnum.精米.code());
                //5AA509820043000100070000
                sj.replace(15, 16, String.valueOf(MachineContainer.machineConfigDto.mode));
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(sj.toString()));
                break;
            case R.id.btnMillP:
                curType = 0;
                StringBuilder sp = new StringBuilder(MachineCmdEnum.胚芽米.code());
                //5AA509820043000100070000
                sp.replace(15, 16, String.valueOf(MachineContainer.machineConfigDto.mode));
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(sp.toString()));
                break;
            case R.id.btnMill:
                handler.postDelayed(runnable, MachineContainer.machineConfigDto.millTimeOut * 1000);
                int jCount = atMillNo.getValue();
                MachineContainer.orderInfoCacheDto.setMakeNum(jCount);
                if (MachineContainer.machineConfigDto.mode == 1) {
                    if (listGoodsSimpleDtos.size() > 0) {
                        MachineContainer.orderInfoCacheDto.setBarnId(listGoodsSimpleDtos.get(0).barnId);
                    }
                } else {
                    if (listGoodsSimpleDtos.size() > 1) {
                        MachineContainer.orderInfoCacheDto.setBarnId(listGoodsSimpleDtos.get(1).barnId);
                    }
                }

                MachineContainer.machineConfigDto.packageWeight = (atPackageWeight.getValue());
                updateConfig();

                String makeRiceCmd = String.format(MachineCmdEnum.碾米.code(), atMillNo.getValue(), MachineContainer.machineConfigDto.packageWeight);
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(makeRiceCmd));
                machineP.postBackMakeRecord(new MakeRecordDto(MachineContainer.machineConfigDto.machineNo, GoodsContainer.getBarnId(), MachineContainer.machineConfigDto.packageWeight, jCount, jCount));
                break;
            case R.id.btnPack:
                ThreadManager.getThreadPollProxy().execute(() -> {
                    int packages = atPackNo.getValue();
                    String cmd = String.format(MachineCmdEnum.打包.code(), packages);
                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(cmd));
                    Logger.v(TAG, "包数:" + packages, MachineContainer.machineConfigDto.logcat);
                    MachineContainer.machineConfigDto.packNo = (atPackNo.getValue());
                    updateConfig();
                });
                break;
            case R.id.btnClearWarnA:
                if (MachineContainer.machineConfigDto.aWarn) {
                    MachineContainer.machineConfigDto.aWarn = false;
                    updateConfig();
                }
                break;
            case R.id.btnClearWarnB:
                if (MachineContainer.machineConfigDto.bWarn) {
                    MachineContainer.machineConfigDto.bWarn = false;
                    updateConfig();
                }
                break;
            case R.id.btn_open_send_valley:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.自动送谷模式.code()));
                tvMode.setText("当前模式：自动送谷，".concat(getGarnerString()));
                MachineContainer.machineConfigDto.microControlMode = 0;
                updateConfig();
                break;
            case R.id.btn_close_send_valley:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.不自动送谷模式.code()));
                tvMode.setText("当前模式：不自动送谷，".concat(getGarnerString()));
                MachineContainer.machineConfigDto.microControlMode = 1;
                updateConfig();
                break;
            case R.id.btn_open_door_mode:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.开门电机开到位.code()));
//                tvMode.setText("当前模式：开关门，".concat(getGarnerString()));
//                MachineContainer.machineConfigDto.microControlMode = 2;
//                updateConfig();
                break;
            case R.id.btn_open_lock_mode:
                if (MachineContainer.machineConfigDto.microControlMode != 2) {
                    ToastUtil.showLongToast(mContext, "请先打开开关门模式");
                } else {
                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.打开电子锁模式.code()));
                    tvMode.setText("当前模式：电子锁，".concat(getGarnerString()));
                    MachineContainer.machineConfigDto.microControlMode = 3;
                    updateConfig();
                }
                break;
            case R.id.btn_open_lamp:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.打开灯箱.code()));
                break;
            case R.id.btn_close_lamp:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.关闭灯箱.code()));
                break;
            case R.id.btn_A:
                tvMode.setText("当前模式：".concat(getModeString()).concat("，A谷仓模式"));
                MachineContainer.machineConfigDto.mode = 1;
                updateConfig();
                StringBuilder sa = new StringBuilder(MachineCmdEnum.胚芽米.code());
                //5AA509820043000100070000
                sa.replace(15, 16, String.valueOf(MachineContainer.machineConfigDto.mode));
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(sa.toString()));
                break;
            case R.id.btn_B:
                tvMode.setText("当前模式：".concat(getModeString()).concat("，B谷仓模式"));
                MachineContainer.machineConfigDto.mode = 2;
                updateConfig();
                StringBuilder sb = new StringBuilder(MachineCmdEnum.胚芽米.code());
                //5AA509820043000100070000
                sb.replace(15, 16, String.valueOf(MachineContainer.machineConfigDto.mode));
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(sb.toString()));
                break;
            case R.id.btn_AB:
                tvMode.setText("当前模式：".concat(getModeString()).concat("，AB谷仓模式"));
                MachineContainer.machineConfigDto.mode = 3;
                updateConfig();
                StringBuilder sab = new StringBuilder(MachineCmdEnum.胚芽米.code());
                //5AA509820043000100070000
                sab.replace(15, 16, String.valueOf(MachineContainer.machineConfigDto.mode));
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(sab.toString()));
                break;
            case R.id.btn_close_door_mode:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.开门电机关到位.code()));
                break;
            case R.id.btn_close_lock_mode:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.关闭电子锁模式.code()));
                break;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private String getGarnerString() {
        if (MachineContainer.machineConfigDto.mode == 1) {
            return "A谷仓模式";
        } else if (MachineContainer.machineConfigDto.mode == 2) {
            return "B谷仓模式";
        } else if (MachineContainer.machineConfigDto.mode == 3) {
            return "AB谷仓模式";
        } else {
            return "A谷仓模式";
        }
    }

    private String getModeString() {
        if (MachineContainer.machineConfigDto.microControlMode == 0) {
            return "自动送谷";
        } else if (MachineContainer.machineConfigDto.microControlMode == 1) {
            return "不自动送谷";
        } else if (MachineContainer.machineConfigDto.microControlMode == 2) {
            return "开关门";
        } else if (MachineContainer.machineConfigDto.microControlMode == 3) {
            return "电子锁";
        } else {
            return "自动送谷";
        }
    }

}
